<template>
  <div class="register">
    <main>
      <h2>用户注册</h2>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        status-icon
        :rules="rules"
        class="demo-ruleForm"
      >
        <el-form-item prop="name">
          <el-input
            v-model="ruleForm.name"
            placeholder="请输入姓名"
            size="large"
            type="text"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item prop="phone">
          <el-input
            v-model="ruleForm.phone"
            placeholder="请输入手机号"
            size="large"
            type="text"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item prop="pass">
          <el-input
            v-model="ruleForm.pass"
            type="password"
            autocomplete="off"
            size="large"
            placeholder="请输入密码"
          />
        </el-form-item>
        <el-form-item prop="pass2">
          <el-input
            v-model="ruleForm.pass2"
            type="password"
            autocomplete="off"
            size="large"
            placeholder="请输入密码"
          />
        </el-form-item>
        <el-form-item prop="role">
          <el-select
            v-model="ruleForm.role"
            size="large"
            placeholder="请选择角色"
            style="width: 100%"
          >
            <el-option
              v-for="item in rolelist"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)"
            >注册</el-button
          >
          <el-button @click="resetForm(ruleFormRef)">去登录</el-button>
        </el-form-item>
      </el-form>
    </main>
  </div>
</template>

<script setup>
import { onMounted, ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { user_register, user_list } from "../api/api";
import { ElNotification } from "element-plus";
import "element-plus/es/components/notification/style/css";
var $router = useRouter();
var ruleForm = reactive({ phone: "", pass: "",pass2: "", name: "", role: "" });
var rolelist = ref([]);
var ruleFormRef = ref();

var resetForm = (ruleFormRef) => {
  $router.push({ path: "/login" });
};

// .then方式
// onMounted((res) => {
//   user_list({}).then((res) => {
//     var arr = res.data.list.map((item)=>{
//     return { label: item.name, value: item._id }
//   })
//   rolelist.value = arr;
//     console.log(rolelist.value);
//   });
// });

// 平级的方式书写
onMounted(async () => {
  var res = await user_list();
  console.log(res);
  var arr = res.data.list.map((item) => {
    return { label: item.name, value: item._id };
  });
  rolelist.value = arr;
  console.log(rolelist.value);
});

const validatePhone = (rule, value, callback) => {
  if (/^1[3-9]\d{9}$/.test(value) == false) {
    callback(new Error("请输入正确的手机号"));
  } else {
    callback();
  }
};
const validatePass = (rule, value, callback) => {
  if (/^\d{4}$/.test(value) == false) {
    callback(new Error("请输入符合要求的密码,必须是4位数字"));
  } else {
    callback();
  }
};
const validatePass2 = (rule, value, callback) => {
  if (value =="") {
    callback(new Error("请输入密码"));
  } else if(value != ruleForm.pass){
    callback(new Error("两次密码输入不一致"))
  }
  else {
    callback();
  }
};
const validateName = (rule, value, callback) => {
  if (value == "") {
    callback(new Error("请输入姓名"));
  } else {
    callback();
  }
};
const validateRole = (rule, value, callback) => {
  if (value == "") {
    callback(new Error("请选择一个角色"));
  } else {
    callback();
  }
};
// 表单验证
const rules = reactive({
  phone: [{ validator: validatePhone, trigger: "blur" }],
  pass: [{ validator: validatePass, trigger: "blur" }],
  pass2: [{ validator: validatePass2, trigger: "blur" }],
  name: [{ validator: validateName, trigger: "blur" }],
  role: [{ validator: validateRole, trigger: "blur" }],
});

// //点击"注册" 手动验证表单, 参数formEl是表单实例, validate是表单实例的方法, 用来验证整个表单.
// const submitForm = (formEl) => {
//   if (!formEl) return;
//   formEl.validate(async (valid) => {
//     //validate验证通过valid为true,否则valid为false
//     if (valid) {
//       //发起注册请求
//       var res = await user_register(ruleForm);
//       if (res.data.code == 200) {
//         //注册成功, 跳转登录页
//         ElNotification({
//           title: "注册通知",
//           message: res.data.msg,
//         });
//         $router.push("/login");
//       } else {
//         //弹框
//         ElNotification({
//           title: "注册通知",
//           message: res.data.msg,
//           type: "error",
//         });
//       }
//     } else {
//       return false;
//     }
//   });
// };




const submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      user_register({phone:ruleForm.phone,pass:ruleForm.pass,name:ruleForm.name,role:ruleForm.role}).then((res) => {
        if (res.data.code == 200) {
          //注册成功, 跳转登录页
          ElNotification({
            title: "注册通知",
            message: res.data.msg,
             type: 'success',
          });
            $router.push({ path: "/login" });
        }else{
            //弹框
            ElNotification({
              title: '注册通知',
              message: res.data.msg,
              type: 'error',
            })
        }
      });
    }else{
         return false
    }
  });
};

</script>

<style lang="scss">
* {
  padding: 0;
  margin: 0;
}
.register {
  border: 1px solid transparent;
  background: url("../assets/bj.png");
  background-size: cover;
  width: 100%;
  height: 100vh;
  main {
    border-radius: 10px;
    width: 400px;
    background-color: white;
    margin: 180px auto;
    padding: 20px;
    box-sizing: border-box;
    h2 {
      text-align: center;
      margin: 10px auto;
    }
    form {
      width: 90%;
      margin: 0 auto;
    }
    .el-form-item__content {
      justify-content: space-around;
    }
  }
}
</style>